﻿using Engine;
using Game;
using GameEntitySystem;
using System;
using TemplatesDatabase;

namespace SAGhoul
{
	public class ComponentEnhancedHealth : Component, IUpdateable
	{
		public const float HealthThreshold = 0.9f;
		public const float FoodThreshold = 0.9f;
		public const float StaminaThreshold = 0.3f;
		public const float StaminaExitThreshold = 0.95f;
		public const float StaminaRegenBoost = 2.5f;
		public const float FoodDeductionRate = 0.05f;
		public const float EnhancedRegenMultiplier = 80f;
		public const float HarmlessRegenMultiplier = 7f;
		public const float FoodDeductionInterval = 1f;
		public const float MinEnhancedDuration = 6f;
		public const float MinFoodLevel = 0.45f; // 最低饱食度阈值
		public const float OriginalStaminaRegenRate = 0.1f;
		public const float PermanentStaminaRegenMultiplier = 0.08f;//常驻体力恢复倍率

		public SubsystemGameInfo m_subsystemGameInfo;
		public ComponentHealth m_componentHealth;
		public ComponentVitalStats m_componentVitalStats;
		public ComponentPlayer m_componentPlayer;
		public UpdateOrder UpdateOrder => UpdateOrder.Default;

		bool m_isEnhanced, m_forceEnhanced;
		float m_foodDeductionTimer, m_enhancedStartTime, m_originalRegenRate;

		public override void Load(ValuesDictionary valuesDictionary, IdToEntityMap idToEntityMap)
		{
			base.Load(valuesDictionary, idToEntityMap);
			m_componentHealth = Entity.FindComponent<ComponentHealth>(throwOnError: true);
			m_componentVitalStats = Entity.FindComponent<ComponentVitalStats>(throwOnError: true);
			m_componentPlayer = Entity.FindComponent<ComponentPlayer>();
			m_subsystemGameInfo = Project.FindSubsystem<SubsystemGameInfo>(throwOnError: true);
			m_originalRegenRate = m_componentHealth.HealFactor;
			m_forceEnhanced = false;
		}

		public void Update(float dt)
		{
			if (m_componentPlayer == null)
				return;

			// 常驻体力恢复（无论是否在增强状态都生效）
			ApplyConstantStaminaRegen(dt);

			float currentHealth = m_componentHealth.Health;
			float currentStamina = m_componentPlayer.ComponentVitalStats.Stamina;
			float currentFood = m_componentPlayer.ComponentVitalStats.Food;
			float currentTime = (float)DateTime.Now.TimeOfDay.TotalSeconds;

			// 简化退出条件：任何情况下饱食度过低都必须退出
			bool mustExitDueToLowFood = currentFood <= MinFoodLevel;
			// 进入增强状态的条件
			bool canTrigger = !m_isEnhanced &&
							currentFood > FoodThreshold &&
							(currentStamina < StaminaThreshold || currentHealth < HealthThreshold);
			// 退出增强状态的条件
			bool canExit = m_isEnhanced &&
						  !m_forceEnhanced &&
						  (currentHealth >= HealthThreshold && currentStamina >= StaminaExitThreshold);
			
			if (canTrigger && !mustExitDueToLowFood)
			{// 进入增强状态
				EnterEnhancedMode();
				m_enhancedStartTime = currentTime;
				m_forceEnhanced = true;
			}
			if (m_isEnhanced && m_forceEnhanced)
			{// 检查最小持续时间
				float enhancedDuration = currentTime - m_enhancedStartTime;
				if (enhancedDuration >= MinEnhancedDuration)
				{
					m_forceEnhanced = false;
				}
			}
			if (m_isEnhanced && (mustExitDueToLowFood || canExit))
			{// 退出增强状态（三个条件满足任一即可退出）
				ExitEnhancedMode();
			}
			if (m_isEnhanced)
			{// 在增强状态下处理饱食度扣除和体力恢复
				ProcessEnhancedMode(dt);
			}
		}

		void EnterEnhancedMode()
		{
			float regenMultiplier = (m_subsystemGameInfo.WorldSettings.GameMode == GameMode.Harmless)
				? HarmlessRegenMultiplier
				: EnhancedRegenMultiplier;

			m_componentHealth.HealFactor = m_originalRegenRate * regenMultiplier;
			m_isEnhanced = true;
			m_foodDeductionTimer = FoodDeductionInterval;
		}
		void ExitEnhancedMode()
		{
			m_isEnhanced = false;
			m_forceEnhanced = false;
			m_componentHealth.HealFactor = m_originalRegenRate;
		}

		void ProcessEnhancedMode(float dt)
		{// 体力恢复（在增强状态下使用更高的恢复速率）
			float staminaRegenRate = StaminaRegenBoost * dt;
			m_componentPlayer.ComponentVitalStats.Stamina += staminaRegenRate;
			m_componentPlayer.ComponentVitalStats.Stamina = Math.Min(1.0f, m_componentPlayer.ComponentVitalStats.Stamina);

			// 饱食度扣除
			m_foodDeductionTimer -= dt;
			if (m_foodDeductionTimer <= 0f)
			{
				m_componentPlayer.ComponentVitalStats.Food = Math.Max(0f,
					m_componentPlayer.ComponentVitalStats.Food - FoodDeductionRate);
				m_foodDeductionTimer = FoodDeductionInterval;
			}
		}
		void ApplyConstantStaminaRegen(float dt)
		{// 处理常驻体力恢复
			if (m_componentPlayer != null && m_componentPlayer.ComponentVitalStats != null)
			{
				// 只在非增强状态下应用常驻恢复，避免重复恢复
				if (!m_isEnhanced)
				{
					float constantStaminaRegen = OriginalStaminaRegenRate * PermanentStaminaRegenMultiplier * dt;
					m_componentPlayer.ComponentVitalStats.Stamina += constantStaminaRegen;
					m_componentPlayer.ComponentVitalStats.Stamina = Math.Min(1.0f, m_componentPlayer.ComponentVitalStats.Stamina);
				}
			}
		}

	}
}